//
//  jaikuAPI+threads.m
//  juhu
//
//  Created by Christian Martick on 22.11.08.
//  Copyright 2008 Christian Martick. All rights reserved.
//

#import "smcJaikuAPI.h"

#define JAIKU_THREAD_URL_FORMAT @"%@.jaiku.com/presence/%@/json?user=%@&personal_key=%@"

@implementation smcJaikuAPI (threads)

#pragma mark private helper

- (NSArray *) threadFromUser: (NSString *) nick withID: (NSString *) threadID
{
	// if thread doesn't exist in dict
	
	NSString *dictKey = [NSString stringWithFormat: @"%@_%@", nick, threadID];
	
	if ([_threads objectForKey: dictKey] == nil)
	{
			// start download
			[self downloadThreadFromUser: nick withID: threadID];
			return nil;
	
	}
		
	return [_threads objectForKey: dictKey];
}

- (void) downloadThreadFromUser: (NSString *) nick withID: (NSString *) threadID
{	
	// start json feed download for user thread
	smcAsyncConnection *connection = [[[smcAsyncConnection alloc] init] autorelease];
	[connection setDelegate: self];
	NSURL * service = [NSURL URLWithString: 
					   [NSString stringWithFormat: 
						JAIKU_THREAD_URL_FORMAT, nick, threadID, _personalKey, _username]];
	
	
	[connection beginDownloadFromURL: service
				   withTimout: 20.0 userAgent: JUHUCLIENT_VERSION 
					  andInfo: [NSDictionary dictionaryWithObjectsAndKeys: 
								@"threadcatch", @"kind",
								threadID, @"ID",
								nick, @"nick", NULL]];

}

- (NSError *) processThreadFeedData: (NSData *) data fromUser: (NSString *) nick andID: (NSString *) threadID
{
	// create dict from data
	NSString *tmp = [NSString stringWithString: [self makeCleanUTF8MutableStringFromData: data]];
	
	NSDictionary *dict = [NSDictionary dictionaryWithJSONString: tmp];
	if (dict != nil)
	{
		// put in dict
		NSString *dictKey = [NSString stringWithFormat: @"%@_%@", nick, threadID];
		[_threads setObject: dict forKey: dictKey];
	}
	else
		return nil;
	
	return nil;	
}

@end
